package com.aube.interact.taste;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.interact.taste.model.CategoryImp;
import com.aube.interact.taste.model.CategoryListModel;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.VideoModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by hill on 16/12/16.
 */

public class AutoPlayView extends FrameLayout {
    private final String TAG = "Aube/AutoPlayView";

    private Context mContext;

    private IPluginBaseListener mBaseListener;
    private Category mCategory;
    private ChannelDetail mChannelDetail;

    private String mLastId="";
    private Handler mHandler;
    private List<ChannelDetail> mNextEpisodesList = new ArrayList<>();

    private static final int MAX_NUM  =10;
    private int mCountDown = 5;

    private int mRootWidth, mRootHeight;
    private int mRootTop, mRootLeft;
    private LinearLayout mRootLy, mReplayLy;
    private LinearLayout mVideosLy, mCheckGoodsLy;

    private TextView mTimerText, mNextVideoTitle;

    private double mRootTopRatio = 0.22;
    private AtomicBoolean mRefreshTimerDisabled = new AtomicBoolean(false);
    private boolean mIsAvailable = false;

    //private RecyclerView mEpisodeList;

    public AutoPlayView(Context context) {
        this(context, null);
    }
    public AutoPlayView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public AutoPlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        Utils.Log(TAG, "[initView]");
        setBackgroundColor(getResources().getColor(R.color.black_60));
        LayoutInflater.from(mContext).inflate(R.layout.aube_intera_layout_video_autoplay, this);
        mRootLy = (LinearLayout) findViewById(R.id.autoplay_root);
        mReplayLy = (LinearLayout) findViewById(R.id.autoplay_replay);
        mVideosLy = (LinearLayout) findViewById(R.id.autoplay_recommendvideos);
        mTimerText = (TextView) findViewById(R.id.autoplay_timertext);
        mCheckGoodsLy = (LinearLayout) findViewById(R.id.autoplay_checkgoods);
        mNextVideoTitle = (TextView) findViewById(R.id.autoplay_videoname);

        mRootWidth = getResources().getDimensionPixelOffset(R.dimen.recommendvideo_width) * 3 + Utils.dip2px(mContext, 30);

        mHandler = new Handler(mContext.getMainLooper());

        mCheckGoodsLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                resetAutoPlayView();
                alphaOut(true);
            }
        });

        mReplayLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                resetAutoPlayView();
                if(mBaseListener != null)
                    mBaseListener.switchVideo(mChannelDetail);
            }
        });
    }

    public void alphaIn() {
        setVisibility(VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                setupRefreshTimer();
            }
        });
        animator.setDuration(300);
        animator.start();
    }

    public void alphaOut(final boolean bShowGoodsStore) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                setVisibility(GONE);
                if(bShowGoodsStore)
                    mBaseListener.showGoodsStore();
            }
        });
        animator.setDuration(300);
        animator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mRootLy.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        mRootHeight = mRootLy.getMeasuredHeight();

        measureChild(getChildAt(0), MeasureSpec.makeMeasureSpec(mRootWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(mRootHeight, MeasureSpec.EXACTLY));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        mRootTop = (int) (getMeasuredHeight() * mRootTopRatio);
        mRootLeft = getMeasuredWidth() / 2 - mRootWidth / 2;
        mRootLy.layout(mRootLeft, mRootTop, mRootLeft + mRootWidth, mRootTop + mRootHeight);
    }

    public void setupPlayerListner(IPluginBaseListener listner) {
        mBaseListener = listner;
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void fetchServerData(Category category, ChannelDetail channelDetail) {
        if(category == null) {
            Utils.Log(TAG, "[fetchServerData] category is null");
            return;
        }

        mCategory = category;
        mChannelDetail = channelDetail;

        HashMap<String, String> params = new HashMap<>();
        params.put(OpenApi.API_METHOD, OpenApi.MODULE_MORE);
        params.put("templateCode", mCategory.templateType);
        params.put("modelCode", mCategory.modelCode);
        params.put("relatedId", mCategory.relatedId);
        if(StringUtils.isNotBlank(mLastId))
            params.put("lastId", mLastId);
        params.put("maxnum", MAX_NUM + "");
        params.put("subModelCode", mCategory.subModelCode);
        BFJSONRequest request = new BFJSONRequest(CategoryListModel.class, params, new Response.Listener<CategoryListModel>() {

            @Override
            public void onResponse(CategoryListModel response) {
                if(response == null || !response.success())
                    return;
                setupServerData(response);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
        HttpRequestLoader.getInstance(mContext).startCacheLoader("", request, true);
    }

    public void setupServerData(CategoryListModel model) {
        Utils.Log(TAG, "[setupServerData] in");

        if(model == null || model.size() <= 0) {
            Utils.Log(TAG, "[setupServerData] model is null");
            return;
        }

        int i = 0;
        for(CategoryImp categoryImp : model.data) {
            if(categoryImp.modelCode.equalsIgnoreCase("modelHead"))
                continue;

            if(!categoryImp.subModelCode.equalsIgnoreCase(mCategory.subModelCode))
                continue;

            boolean bCurrentVideo = false;
            for(Object obj : categoryImp.dataDetail) {
                final VideoModel videoModel = new VideoModel();

                LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
                Iterator<String> keyIterator= lhm.keySet().iterator();
                while (keyIterator.hasNext()) {
                    String key = keyIterator.next();
                    Object value = lhm.get(key);
                    videoModel.setItem(key, value);
                }

                if(bCurrentVideo && mNextEpisodesList.size() < 3) {
                    mNextEpisodesList.add(videoModel.toChannelDetail());

                    VideoGrid videoGrid = new VideoGrid(mContext);
                    videoGrid.initView(videoModel);
                    videoGrid.setLayoutParams(i++);
                    videoGrid.setTag(0);
                    videoGrid.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            resetAutoPlayView();
                            if(mBaseListener != null)
                                mBaseListener.switchVideo(videoModel.toChannelDetail());
                        }
                    });
                    Utils.Log(TAG, "[setupServerData] mVideosLy add one item");
                    mVideosLy.addView(videoGrid);
                }

                if(mChannelDetail.videoid.equals(videoModel.videoid)) {
                    Utils.Log(TAG, "[setupServerData] current episode found");
                    bCurrentVideo = true;
                }
            }

            if(mNextEpisodesList.size() == 0) {
                mTimerText.setText("视频播放完了~");
                setVisibility(GONE);
            } else {
                mNextVideoTitle.setText("《" + mNextEpisodesList.get(0).videoTitle + "》");
            }
        }
    }

    public void resetAutoPlayView() {
        mIsAvailable = false;
        mCountDown = 5; //reset to 5.
        mTimerText.setText("5 秒后自动播放下一集");
        mHandler.removeCallbacks(mRefreshRunnable);
    }

    private void setupRefreshTimer() {
        mHandler.postDelayed(mRefreshRunnable, 1000);
    }

    private Runnable mRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            if(mCountDown > 0) {
                mTimerText.setText(String.valueOf(--mCountDown) + " 秒后自动播放下一集");
                setupRefreshTimer();
            } else {
                if(mBaseListener != null && mNextEpisodesList.size() != 0)
                    mBaseListener.switchVideo(mNextEpisodesList.get(0));
            }
        }
    };

    public boolean isAvailable() {
        return mIsAvailable;
    }

    public void setAvailability(boolean value) {
        mIsAvailable = value;
    }

    public void resumeFromGoodsStore() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f);
        animator.setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                setVisibility(VISIBLE);
            }
        });
        animator.start();
        setupRefreshTimer();
    }

    public void setGoodsLyVisibility(boolean bShowGoodsLy) {
        if(!bShowGoodsLy)
            mCheckGoodsLy.setVisibility(GONE);
    }
}
